const bcrypt = require('bcryptjs')
const mysql = require('mysql2/promise')

async function createSpecificAdmin () {
  const connection = await mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'hezi5200',
    database: 'novel_platform'
  })

  try {
    console.log('🔍 检查数据库表结构...')

    // 检查users表结构
    const [columns] = await connection.execute('DESCRIBE users')
    console.log('📋 users表字段:')
    console.table(
      columns.map(col => ({
        Field: col.Field,
        Type: col.Type,
        Null: col.Null,
        Default: col.Default
      }))
    )

    console.log('\n🔍 检查指定邮箱是否已存在...')

    // 检查指定邮箱是否已存在
    const [existing] = await connection.execute(
      'SELECT * FROM users WHERE email = ?',
      ['1477042095@qq.com']
    )

    if (existing.length > 0) {
      console.log('⚠️  邮箱 1477042095@qq.com 已存在，正在更新密码...')

      // 更新现有用户的密码
      const hashedPassword = await bcrypt.hash('GKL9512357', 12)

      await connection.execute(
        'UPDATE users SET password_hash = ?, is_vip = 1, coins = 9999 WHERE email = ?',
        [hashedPassword, '1477042095@qq.com']
      )

      console.log('✅ 现有账号已更新为管理员权限！')
    } else {
      console.log('📝 正在创建新的管理员账号...')

      // 加密密码
      const hashedPassword = await bcrypt.hash('GKL9512357', 12)

      // 创建新管理员账号
      await connection.execute(
        'INSERT INTO users (username, email, password_hash, nickname, is_vip, coins, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())',
        [
          'admin_gkl',
          '1477042095@qq.com',
          hashedPassword,
          '超级管理员',
          1,
          9999
        ]
      )

      console.log('✅ 新管理员账号创建成功！')
    }

    console.log('')
    console.log('🔑 管理员登录信息：')
    console.log('   邮箱: 1477042095@qq.com')
    console.log('   密码: GKL9512357')
    console.log('')

    // 验证账号创建结果
    const [result] = await connection.execute(
      'SELECT id, username, email, nickname, is_vip, coins FROM users WHERE email = ?',
      ['1477042095@qq.com']
    )

    if (result.length > 0) {
      console.log('✅ 账号验证成功:')
      console.table(result)
    }

    // 显示所有用户
    console.log('\n📋 所有用户列表:')
    const [allUsers] = await connection.execute(
      'SELECT id, username, email, nickname, is_vip, coins FROM users ORDER BY id'
    )
    console.table(allUsers)
  } catch (error) {
    console.error('❌ 错误:', error.message)
    console.error('详细错误:', error)
  }

  await connection.end()
  process.exit(0)
}

console.log('🚀 开始创建指定管理员账号...')
createSpecificAdmin()
